﻿using DimensionsHelper.Common.Contracts.TableFormatter;

namespace DimensionsHelper.Client.WinUi.ViewModels;

public partial class TableFormatterOutputFileViewModel : FileViewModel
{
    public TableFormatterOutputFileViewModel()
    {
        Filter = FileFilters.Excel;
        Files = [];
    }

    public ObservableCollection<TableFormatterInputFileViewModel> Files
    {
        get;
    }


    private bool CsvFileExists(string fileName) => FileExists(Files, fileName);


    [RelayCommand]
    private async Task SelectFiles()
    {
        IReadOnlyList<string> files = await App.GetService<IFilePikerService>()
            .PickMultipleFilesAsync(FileFilters.Csv);

        foreach (string file in files)
        {
            if (string.IsNullOrEmpty(file) || CsvFileExists(file))
            {
                continue;
            }

            TableFormatterInputFileViewModel inputFile = new()
            {
                ExistPredicate = CsvFileExists,
                RemoveCallback = fileViewModel =>
                {
                    if (fileViewModel is TableFormatterInputFileViewModel vm)
                    {
                        Files.Remove(vm);
                    }
                },
                FileName = file,
                Filter = FileFilters.Csv
            };

            Files.Add(inputFile);
        }
    }


    public IReadOnlyList<TableInputFileInfo> GetCsvInputFileInfos()
    {
        return Files.DistinctBy(f => f.FileName, PathEqualityComparer.Instance)
            .Select(f => f.GetFileInfo())
            .Where(info => info != null)
            .Cast<TableInputFileInfo>()
            .ToList();
    }
}